<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Client\ConnectionException;

class HttpClientService
{
    public function get(string $url, array $query = [], array $headers = [])
    {
        return $this->sendRequest('get', $url, $query, $headers);
    }

    public function post(string $url, array $data = [], array $headers = [])
    {
        return $this->sendRequest('post', $url, $data, $headers);
    }

    public function put(string $url, array $data = [], array $headers = [])
    {
        return $this->sendRequest('put', $url, $data, $headers);
    }

    public function delete(string $url, array $headers = [])
    {
        return $this->sendRequest('delete', $url, [], $headers);
    }

    public function postJson(string $url, array $data = [], array $headers = [])
    {
        $headers = array_merge($headers, ['Content-Type' => 'application/json']);
        return $this->sendRequest('post', $url, $data, $headers, true);
    }

    // 通用的请求方法，处理所有的 HTTP 方法请求
    protected function sendRequest(string $method, string $url, array $data = [], array $headers = [], bool $asJson = false)
    {
        try {
            $response = Http::withHeaders($headers);
            if ($asJson) {
                $response = $response->asJson();
            }
            $response = $response->$method($url, $data)->throw(); // 发送请求并使用 throw() 方法来自动处理错误状态码
            return $response->json();  // 返回或处理 JSON 数据
        } catch (RequestException $e) { // 一般是400 500错误
            throw new \Exception('http错误码： ' . $e->getCode() . " 请求失败: " . $e->getMessage());
        }  catch (ConnectionException $e) { // 一般是url的域名部分发生错误 如baiddu.com
            throw new \Exception("请检查url: " . $url . ' 消息： ' . $e->getMessage() . PHP_EOL);
        }
    }
}
